<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="绩效名称">
                <a-input
                  v-model="queryParam.performanceName"
                  placeholder="请输入绩效名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="员工姓名">
                <a-input
                  v-model="queryParam.name"
                  placeholder="请输入员工姓名" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="任务名称">
                <a-input
                  v-model="queryParam.taskName"
                  placeholder="请输入任务名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="() => $refs.table.refresh()">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="任务类型">
                <a-select
                  :style="{ width: '100%'}"
                  v-model="queryParam.type"
                  placeholder="请选择任务类型">
                  <a-select-option :value="1">项目绩效</a-select-option>
                  <a-select-option :value="2">内部绩效</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="创建时间">
                <a-range-picker
                  valueFormat="YYYY-MM-DD 00:00:00"
                  :placeholder="['开始日期','结束日期']"
                  v-model="queryParam.createTime" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="handleAdd">新建</a-button>
        <a-button
          type="primary"
          icon="plus"
          v-if="exportPermission"
          @click="exportData">导出</a-button>
        <span style="font-weight: bold;float: right;font-size: 18px">绩效总分:{{ performanceCategory }}</span>
      </div>
      <div>
        <a-spin :spinning="confirmLoading">
          <s-table
            ref="table"
            size="default"
            rowKey="performanceId"
            :columns="columns"
            :data="loadData"
            showPagination="auto"
            :customRow="tableCustomRow">
            <span
              slot="serial"
              slot-scope="text, _record, index">
              {{ index + 1 }}
            </span>
            <span
              slot="createTime"
              slot-scope="text, _record">
              {{ _record.createTime ? _record.createTime.split(' ')[0] : '' }}
            </span>
            <span
              slot="action"
              slot-scope="text, _record">
              <template>
                <a v-if="update" @click="handleEdit(_record)">配置</a>
                <a-divider v-if="update" type="vertical" />
                <a v-if="deleteBtn" @click="() => deletePerformance(_record)">
                  删除
                </a>
              </template>
            </span>
          </s-table>
        </a-spin>
      </div>
      <!-- isProjectPro: true
          项目绩效 可以改1.备注 2.绩效名称 3.依据。  (展示任务。其他项disable
          isProjectPro: false
          内部绩效 1.任务不展示，其他项编辑时可以编辑
       -->
      <create-form
        ref="createModal"
        :visible="visible"
        :allUsers="allUsers"
        :isProjectPro="isProjectPro"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'
// exportPerformance
import {
  getPerformanceList,
  allStaff,
  // getALlTaskLevel2,
  savePerformance,
  deletePerformance,
  updatePerformance,
  exportPerformance
} from '@/api/manage'
import { columns } from './config'
import CreateForm from './modules/CreateForm'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'
import { message, Modal } from 'ant-design-vue'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
                       // 权限参数
      list: false, // 列表
      save: false, // 加
      deleteBtn: false, // 删
      update: false, // 改
      exportPermission: false, // 绩效导出
      visible: false,
      confirmLoading: false,
      advanced: false,
      queryParam: {},
      record: undefined,
      isAdd: false,
      allUsers: undefined,
      tasks: undefined,
      exportParam: undefined,
      isProjectPro: false,
      performanceCategory: 0,
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        if (this.queryParam.createTime) {
          param.createTimeBegin = this.queryParam.createTime[0]
          param.createTimeEnd = this.queryParam.createTime[1]
        }
        this.exportParam = Object.assign({}, param, requestParameters)
        return this.list && getPerformanceList(this.exportParam).then(res => {
          this.performanceCategory = res.performanceCategory
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  created () {
        // 点击查看
    this.list = isInMenu(this.menu, 'ROLE_but:performance:list') && isInMenu(this.menu, 'ROLE_but:performance:info')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:performance:save') && isInMenu(this.menu, 'ROLE_but:user:select')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:performance:update') && isInMenu(this.menu, 'ROLE_but:user:select')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:performance:delete')
    // 导出数据
    this.exportPermission = isInMenu(this.menu, 'ROLE_but:performance:export')
  },
  mounted () {
    isInMenu(this.menu, 'ROLE_but:user:select') && allStaff({}).then(res => {
      this.allUsers = res.data
    })
    // getALlTaskLevel2({ taskLevel: 2 }).then(res => {
    //   this.tasks = res.data
    // })
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    deletePerformance (record) {
      Modal.confirm({
        title: '删除合同',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.confirmLoading = true
          deletePerformance({ performanceId: record.performanceId })
            .then(() => {
              this.$refs.table.refresh()
              message.success('删除绩效成功')
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleAdd () {
      this.isProjectPro = false
      this.visible = true
      this.isAdd = true
      const form = this.$refs.createModal.form
      this.$nextTick(() => {
        form.setFieldsValue({ type: 2 })
      })
    },
    handleEdit (record) {
      this.visible = true
      this.isAdd = false
      this.record = record
      const form = this.$refs.createModal.form

      if (record.type === 1) {
        this.isProjectPro = true
      } else {
        this.isProjectPro = false
      }
      this.$nextTick(() => {
        form.setFieldsValue(record)
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.isAdd) {
            savePerformance(values)
              .then(res => {
                if (res.code === 0) {
                  this.visible = false
                  this.$refs.table.refresh()
                  this.$message.info('新增成功')
                  form.resetFields()
                }
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            updatePerformance(Object.assign({}, values, { performanceId: this.record.performanceId }))
              .then(res => {
                if (res.code === 0) {
                  this.visible = false
                  this.$refs.table.refresh()
                  this.$message.info('配置成功')
                  form.resetFields()
                  // this.customLoading = false
                }
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.performanceId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.performanceId
            this.record = record
            this.staffInfo = record
          }
        }
      }
    },
    exportData () {
      exportPerformance(this.exportParam).then(res => {
        const fileName = '员工绩效.xlsx'
        const objectUrl = URL.createObjectURL(
          new Blob([res.data], { type: 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        )
        // 文件地址
        const link = document.createElement('a')
        link.download = fileName
        link.href = objectUrl
        link.click()
      })
    }
  }
}
</script>
